/**
 * @author zhaojiuyi
 * @date 2022/5/25-21:55
 * @version 1.0.0
 */
import {Message} from 'element-ui';

export default {
  //深拷贝
  // 该方法能正确处理的对象只有 Number, String, Boolean, Array, 扁平对象，即那些能够被 json 直接表示的数据结构，不能拷贝方法
  jsonToParse: (data) => {
    return JSON.parse(JSON.stringify(data));
  },
  successMessage: (msg) => {
    Message({
      message: msg,
      type: 'success'
    });
  },
  errorMessage: (msg) => {
    Message({
      message: msg,
      type: 'error'
    });
  },

  //获取cookie的指定值
  getCookie: (cname) => {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i].trim();
      if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
    }
    return null;
  },
  setCookie: (cname, cvalue, exdays) => {
    // key value 生效时间
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
  },

  //节流函数
  throttl: (func, deplay) => {
    let timer = null
    return function () {
      if (timer) return null
      timer = setTimeout(() => {
        clearTimeout(timer)
      }, deplay)
      func()
    }
  },
  // axios流下载
  axiosDownload: (response) => {
    const blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
    const downloadElement = document.createElement('a');
    const href = window.URL.createObjectURL(blob);
    let contentDisposition = response.headers['content-disposition'];  //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    let part = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
    let result = part.exec(contentDisposition);
    let filename = decodeURI(result[1]);
    downloadElement.style.display = 'none';
    downloadElement.href = href;
    downloadElement.download = filename; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    return true;
  },
  deepClone: function (obj){
    if (typeof obj !== 'object' || obj === undefined) {
      // 如果obj不是object类型或者为undefined,不做处理直接返回
      return obj;
    }
    let result;  // 声明一个返回结果
    if (obj instanceof Array) {  // 判断obj是数组还是对象
      result = [];
    } else {
      result = {};
    }
    for (let key in obj) {
      // 确保key 不是原型上的属性
      if (obj.hasOwnProperty(key)) {
        // 递归调用，一直往下挖，最终完成深拷贝
        result[key] = this.deepClone(obj[key]);
      }
    }
    return result;  // 返回一份完全独立的拷贝
  }



}

